const fs = require('fs')
const path = require('path')

module.exports = {
    uploadUserPic:async(ctx,next) => {
        try{
            const file = ctx.request.files.file;
            console.log("file",file);
            const fileData = fs.readFileSync(file.filepath);
            console.log("fileData",fileData);
            console.log(ctx.state.userNum);
            const userPicFileName = ctx.state.userNum +'.'
            + file.originalFilename.substring(file.originalFilename.lastIndexOf('.') +1);
            console.log("userPicFileName",userPicFileName);
            let filePath = path.join(process.cwd(),'/public/upload/') + `${userPicFileName}`;
            console.log("filePath",filePath);
            fs.writeFileSync(filePath,fileData); //filePath 写入文件的路径；fileData 写入文件的内容  
            ctx.body = {
                success:true,
                data:'',
                info:{msg:'上传用户数据成功'},
                code:200
            }
        }catch(error){
            console.log(erroe);
            ctx.body = {
                success:false,
                data:'',
                info:{msg:'上传用户数据失败'},
                code:200
            }
        }
    },
    downloadUserPic:async(ctx,next) => {
        try{
            const downFileName = ctx.state.userNum + '.png'
            let filePath = path.join(process.cwd(),'./public/upload/')+ `${downFileName}`;
            console.log(filePath);
            if(fs.existsSync(filePath)){//如果目录存在 返回 true ，如果目录不存在 返回false
                ctx.body = fs.createReadStream(filePath) //filePath 读出文件的路径
                // console.log("ctx.body",ctx.body);
            }else{
                ctx.body={}
            }
        }catch(error){
            console.log(error);
            ctx.body = {
                success:false,
                data:'',
                info:{msg:'下载用户图片失败'},
                code:200
            }
        }


    }

}